# -*- coding:utf-8 -*-
"""
懒加载 -- Ajax加载
一组有24张图片
第一个请求是从第25张图片开始  24
"""

from urllib.parse import urlencode
import requests
import re
import os


class ImageData(object):
    def __init__(self):
        self.number = 1
        self.url = "https://www.duitang.com/napi/blogv2/list/by_search/?"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
        }
        self.name = input("请输入你要抓取的类型：")

        # 判断同级目录下是否有某个文件夹，如果没有，则自动创建
        if not os.path.exists(self.name):
            os.mkdir(self.name)

    # 向堆糖网发起请求
    def gat_data_index(self, num):
        params = {
            "kw": self.name,
            "after_id": "{}".format(num * 24),
            "type": "feed",
            "include_fields": "top_comments,is_root,source_link,item,buyable,root_id,status,like_count,like_id,sender,album,reply_count,favorite_blog_id",
            "_type": "",
            "_": "1695453939175"
        }
        url = self.url + urlencode(params)
        response = requests.get(url, headers=self.headers)
        if response.status_code == 200:
            return response.text
        else:
            return None

    # 使用正则进行数据解析
    def parse_image_url(self, response):
        data_list = re.findall(r'"path":"(.*?)"', response)  # 使用非贪婪解析
        # print(data_list)    # 测试结果问题
        for url in data_list:
            self.save_image(url)

    # 保存图片
    def save_image(self, url):
        # os.path.splitext(url)[-1] 提取连接后缀
        with open(f"./{self.name}/%d" % self.number + os.path.splitext(url)[-1], "wb") as f:
            resp = requests.get(url).content
            f.write(resp)
            print(f"第{self.number}张图片保存成功")
            self.number += 1

    # 实现主要业务
    def main(self):
        for num in range(0, 3):
            response = self.gat_data_index(num)
            # print(response)      # 测试结果
            self.parse_image_url(response)


if __name__ == '__main__':
    image = ImageData()
    image.main()
